package com.javawork.juc.one;

import java.util.concurrent.*;

/**
 * @author zhangxiaolu
 * @date 2023-02-05 15:02
 */
public class FutureTaskDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(new MyThread2());
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();
//        futureTask.get(1, TimeUnit.SECONDS);
//        System.out.println(futureTask.get());//必须等到结果才会离开，容易导致阻塞，建议放在程序最后
        System.out.println(Thread.currentThread().getName() + "\t 忙其他任务");
        while (true) {
            if (futureTask.isDone()) {
                System.out.println(futureTask.get());
                break;
            } else {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("越催越慢，再催熄火");
            }
        }

    }
}

class MyThread implements Runnable {

    @Override
    public void run() {

    }
}

class MyThread2 implements Callable<String> {

    @Override
    public String call() throws Exception {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("------come in call -----");
        return "hello callable";
    }
}